package main.java.com.lee.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2022/2/11
 */
public class ReadWriteLockDemo {

    static Map<String, String> common = new HashMap<>();
    public static void main(String[] args) throws InterruptedException {

        common.put("a", "aaa");
        common.put("b", "bbb");
        ReadWriteLock lock = new ReentrantReadWriteLock();
        Lock readLock = lock.readLock();
        Lock writeLock = lock.writeLock();
        Thread t1 = new Thread("t1") {
            @Override
            public void run() {
                try {
                    read(readLock);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        Thread t2 = new Thread("t2") {
            @Override
            public void run() {
                try {
                    read(readLock);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        Thread t3 = new Thread("t3") {
            @Override
            public void run() {
                try {
                    read(readLock);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        Thread t4 = new Thread("t4") {
            @Override
            public void run() {
                try {
                    write(writeLock);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        Thread t5 = new Thread("t5") {
            @Override
            public void run() {
                try {
                    read(readLock);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();

        t1.join();
        t2.join();
        t3.join();
        t4.join();
        t5.join();

    }

    private static void read(Lock lock) throws InterruptedException {
        lock.lockInterruptibly();
        try {
            System.out.println(System.currentTimeMillis() +" :"+ Thread.currentThread().getName() + ": 读取资源" + common.get("a"));
            Thread.sleep(1000);
        } finally {
            lock.unlock();
        }
    }

    private static void write(Lock lock) throws InterruptedException {
        lock.lockInterruptibly();
        try {
            common.put("d","ddd");
            System.out.println(System.currentTimeMillis() +" :"+ Thread.currentThread().getName() + ": 写入资源d");
        }finally {
            lock.unlock();
        }
    }
}
